import {
  createRouter,
  createWebHashHistory,
  RouterView
} from 'vue-router'
import store from '@/store'
import {
  h,
  render
} from 'vue'


const Layout = () => import('../views/Layout.vue')

const Home = () => import('@/views/home/Home.vue')

const TopCategory = () => import("@/views/category/index.vue")
const SubCategory = () => import("@/views/category/Sub.vue")
const Goods = () => import("@/views/goods/index.vue")

const Login = () => import("@/views/login/index.vue")
const Callback = () => import("@/views/login/components/callback.vue")

const Cart = () => import("@/views/cart/index.vue")

const PayCheckout = () => import('@/views/member/pay/checkout')
const payIndex = () => import('@/views/member/pay/index.vue')
const payResult = () => import('@/views/member/pay/result.vue')

const MemberLayout = () => import('@/views/member/Layout.vue')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order/orderIndex.vue')
const MemberDetail = () => import('@/views/member/order/detail.vue')

const routes = [{
  path: '/',
  component: Layout,
  children: [{
      path: '/',
      component: Home
    },
    {
      path: '/category/:id',
      component: TopCategory
    }, {
      path: '/category/sub/:id',
      component: SubCategory
    },
    {
      path: '/product/:id',
      component: Goods
    },
    {
      path: '/cart',
      component: Cart
    },
    {
      path: '/member/checkout',
      component: PayCheckout
    },
    {
      path: '/member/pay',
      component: payIndex
    },
    {
      path: '/pay/callback',
      component: payResult
    },
    {
      path: '/member',
      component: MemberLayout,
      children: [{
          path: '',
          component: MemberHome
        },
        {
          path: 'order',
          // vue3.0 需要有路由嵌套关系才能模糊匹配    
          component: {
            render: () => h(RouterView)
          },
          children: [{
              path: '',
              component: MemberOrder
            },
            {
              path: ':id',
              component: MemberDetail
            }
          ]
        }

      ]
    }
  ]
}, {
  path: '/login',
  component: Login
}, {
  path: '/login/callback',
  component: Callback
}, ]

// 创建路由实例
const router = createRouter({
  // 使用hash方式实现路由
  history: createWebHashHistory(),
  // 配置路由规则，写法和之前一样
  routes,
  // 滚动行为
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return {
      top: 0
    }
  },
})

router.beforeEach((to, from, next) => {
  // 用户信息
  const {
    token
  } = store.state.user.profile
  if (to.path.startsWith('/member') && !token) {
    next({
      path: '/login',
      query: {
        redirectUrl: to.fullPath
      }
    })
  } else {
    next()
  }
})

export default router